package com.ruyuan.rapid.common.config;

import lombok.Data;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

@Data
public class Rule implements Comparable<Rule>, Serializable {

    private static final long serialVersionUID = 1L;

    private String id;

    private String protocol;

    private Integer order;

    private Set<Rule.FilterConfig> filterConfigs = new HashSet<>();


    public boolean addFilterConfig(Rule.FilterConfig filterConfig) {
        return filterConfigs.add(filterConfig);
    }



    public Rule.FilterConfig getFilterConfig(String id){
        for(Rule.FilterConfig filterConfig : filterConfigs) {
            if(filterConfig.getId().equalsIgnoreCase(id)) {
                return filterConfig;
            }
        }
        return null;
    }

    public boolean hashId(String id) {
        for(Rule.FilterConfig filterConfig : filterConfigs) {
            if(filterConfig.getId().equalsIgnoreCase(id)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int compareTo(Rule o) {
        int orderCompare = Integer.compare(getOrder(), o.getOrder());
        if(orderCompare == 0) {
            return getId().compareTo(o.getId());
        }
        return orderCompare;
    }


    /**
     * 过滤器配置类
     */
    public static class FilterConfig{

        private String id;

        private String config;
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getConfig() {
            return config;
        }

        public void setConfig(String config) {
            this.config = config;
        }

        @Override
        public boolean equals(Object o) {
            if(this == o) return true;
            if((o == null) || getClass() != o.getClass()) return false;
            FilterConfig that = (FilterConfig)o;
            return id.equals(that.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }
}
